//
//  CreateAdvertisingViewController.swift
//  iModern
//
//  Created by Ralf on 7/29/15.
//  Copyright (c) 2015 com.starlooking. All rights reserved.
//

import UIKit

class CreateAdvertisingViewController: TableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate
{
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let screen      = UIScreen.mainScreen().bounds

    var attachments = NSMutableArray()
    let contentData = NSMutableDictionary()

    override func viewDidLoad()
    {
        super.viewDidLoad()

        self.tableView.registerNib(UINib(nibName: "CreateAdvertisingImageCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "IMAGE")
        self.tableView.registerNib(UINib(nibName: "CreateAdvertisingViewDescriptionCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "DESCRIPTION")
        self.tableView.registerNib(UINib(nibName: "CreateAdvertisingViewAddCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "ADD")

        attachments.addObject(NSMutableDictionary())

        initBackButton()
        initNextButton()
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return getNumberOfCell()
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let numberOfCell = getNumberOfCell()

        if indexPath.row == numberOfCell - 1
        {
            let cell = tableView.dequeueReusableCellWithIdentifier("ADD", forIndexPath: indexPath) as! CreateAdvertisingViewAddCell
            cell.backgroundColor = Theme.theme_color
            cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            return cell
        }
        else
        {
            if indexPath.row % 2 == 0
            {
                let cell       = tableView.dequeueReusableCellWithIdentifier("IMAGE", forIndexPath: indexPath) as! CreateAdvertisingImageCell
                let index      = indexPath.row / 2
                let attachment = attachments[index] as! NSMutableDictionary
                cell.setData(attachment)

                return cell
            }
            else
            {
                let cell       = tableView.dequeueReusableCellWithIdentifier("DESCRIPTION", forIndexPath: indexPath) as! CreateAdvertisingViewDescriptionCell
                let attachment = attachments[(indexPath.row / 2)] as! NSMutableDictionary
                cell.setData(attachment)
                return cell
            }
        }
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        let numberOfCell = getNumberOfCell()

        if indexPath.row == numberOfCell - 1
        {
            return 30
        }
        else
        {
            if indexPath.row % 2 == 0
            {
                return screen.width
            }
            else
            {
                return 80
            }
        }
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        let numberOfCell = getNumberOfCell()

        if indexPath.row == numberOfCell - 1
        {
            let lastAttachment = attachments[attachments.count - 1] as! NSMutableDictionary
            let lastImage      = lastAttachment["image"] as? UIImage
            if lastImage != nil
            {
                attachments.addObject(NSMutableDictionary())
                tableView.reloadData()

                let numberOfCell = getNumberOfCell()

                let index = NSIndexPath(forRow: numberOfCell - 1, inSection: 0)
                tableView.scrollToRowAtIndexPath(index, atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)
            }
        }
        else
        {
            if indexPath.row % 2 == 0
            {
                let cell = tableView.cellForRowAtIndexPath(indexPath) as! CreateAdvertisingImageCell

                if cell.getPreviewImageView().image == nil
                {
                    
                    let alertContorller = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
                    let alertCancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
                    let alertA = UIAlertAction(title: "相机", style: UIAlertActionStyle.Default) {
                        (action: UIAlertAction!) -> Void in
                        self.takePhoto()
                    }
                    let alertB = UIAlertAction(title: "相册", style: UIAlertActionStyle.Default) {
                        (action: UIAlertAction!) -> Void in
                        self.choosePhotoFromLibrary()
                    }
                    alertContorller.addAction(alertCancel)
                    alertContorller.addAction(alertA)
                    alertContorller.addAction(alertB)
                    self.presentViewController(alertContorller, animated: true, completion: nil)
                }
//                choosePhotoFromLibrary()
            }
        }
    }

    func getNumberOfCell() -> Int!
    {
        return attachments.count * 2 + 1
    }


    func takePhoto()
    {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.allowsEditing = true
        imagePicker.sourceType = .Camera
        appDelegate.navigationController.presentViewController(imagePicker, animated: true)
        {

        }
    }

    func choosePhotoFromLibrary()
    {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.allowsEditing = true
        imagePicker.sourceType = .PhotoLibrary

        appDelegate.navigationController.presentViewController(imagePicker, animated: true)
        {

        }
    }

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject:AnyObject]!)
    {
        let attachment = attachments[attachments.count - 1] as! NSMutableDictionary
//        var preview = attachment["image"] as? UIImage
//        if preview == nil
//        {
//            attachment = attachments[0] as! NSMutableDictionary
//        }
//        else
//        {
//            attachment = NSMutableDictionary()
//            attachments.addObject(attachment)
//        }

        attachment.setObject(image, forKey: "image")

        tableView.reloadData()

        appDelegate.navigationController.dismissViewControllerAnimated(true, completion: nil)
    }

    func initNextButton()
    {
        let button = UIBarButtonItem(image: UIImage(named: "Next-Small.png")!.imageWithRenderingMode(.AlwaysOriginal), style: .Plain, target: self, action: "loadFormView:")

        self.navigationItem.rightBarButtonItem = button
    }

    @IBAction func loadFormView(sender: AnyObject)
    {
        self.view.endEditing(true)

        for item in attachments
        {
            print(item["description"] as? String)
        }

        let attachment  = attachments[0] as! NSMutableDictionary
        let image       = attachment["image"] as? UIImage
        let description = attachment["description"] as? String
        
        let filter = SensitiveWordsFilter()
        let valid: Bool = filter.validating(description)
        if !valid
        {
            self.alertWarningMessage("你填写的信息可能包含敏感内容.")
            return
        }

        let last         = attachments.lastObject as! NSMutableDictionary
        let image2       = last["image"] as? UIImage
        let description2 = last["description"] as? String


        if image == nil || description == nil || description == "描述" || image2 == nil || description2 == nil || description2 == "描述"
        {
            return
        }
        else
        {
            let controller = CreateAdvertisingFormViewController()
            controller.attachments = attachments
            self.pushViewController(controller)
        }
    }
}
